﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CodeGenerator
{
    public partial class Form1 : Form
    {
        private DwarfParser parser;
        private DwarfScanner scanner;

        public Form1()
        {
            InitializeComponent();
            scanner = new DwarfScanner();
            parser = new DwarfParser(scanner);

            parser.ParseError += OnParserErrorEventHandler;
        }

        private void ParseFile(string filePath)
        {
            this.Text = "Dwarves - " + filePath;
            listBox.Items.Clear();
            scanner.SetText(File.ReadAllText(filePath));
            parser.Parse();

            AsTree tree = parser.GetTree();
            VisualizeTree(tree);
        }

        public void OnParserErrorEventHandler(object sender, SimpleEventArgs args)
        {
            listBox.Items.Add(args.Info);
        }

        private void VisualizeTree(AsTree tree)
        {
            CodeGenVisitor codeGenVisitor = new CodeGenVisitor();
            string res = codeGenVisitor.GenerateCode(tree);
            richTextBox.Text = res;

            AstPrintVisitor astPrintVisitor = new AstPrintVisitor();
            res = astPrintVisitor.PrintTree(tree);
            richTextBoxRight.Text = res;
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = getTestFilesFolderPath();
            ofd.Multiselect = false;
            ofd.CheckPathExists = true;
            ofd.CheckFileExists = true;
            ofd.AddExtension = true;
            ofd.Filter = "Dwarf files(.dwarf)|*.dwarf|Simple text files(.txt)|*.txt|All files|(*.*)";

            if (ofd.ShowDialog(this) == DialogResult.OK)
            {
                ParseFile(ofd.FileName);
            }
        }

        private string getTestFilesFolderPath()
        {
            return System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + @"\test";
        }
    }
}
